//
//  HOAppController.m
//  WeiDu_1_0
//
//  Created by foguo-mac-1 on 01/07/16.
//  Copyright (c) 2016 WeiDu Energy Tech. All rights reserved.
//

#import "HOAppController.h"
#import "HOUIMgr.h"
#import "HOConstants.h"
#import "SBJson5.h"
#import "NSString+MD5Addition.h"
#import "UIDevice+IdentifierAddition.h"
#import "HOUtils.h"
#import "HOGlobalData.h"
#import "HOJPushHandler.h"
#import "HOAppController.h"

@interface HOAppController()
@property(nonatomic, retain)NSDictionary *caiyunABDic;
@end
@implementation HOAppController

- (void)checkVersion
{
    [self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_AppVersion}];
}


#pragma mark - Caiyun Api

- (void)sendCaiyunRequestWithParams:(NSDictionary *)dic
{
	NSMutableDictionary *copyDic = [[NSMutableDictionary alloc] initWithDictionary:dic];
	[copyDic setObject:kHO_METHOD_Get forKey:kHO_FIELD_Method];
	[copyDic setObject:[NSNumber numberWithInt:HO_SERVICE_CAIYUN] forKey:kHO_FIELD_Service];
	[copyDic setObject:CaiyunBaseUrl forKey:kHO_FIELD_FullUrl];
	
	[self sendRequestWithParams:copyDic
					withModules:nil];
	[copyDic release];
}

- (void)sendCaiyunRequestWithParams:(NSDictionary *)dic withNeedCheckAccessToken:(BOOL)needCheckAccessToken
{
	NSMutableDictionary *copyDic = [[NSMutableDictionary alloc] initWithDictionary:dic];
	[copyDic setObject:kHO_METHOD_Get forKey:kHO_FIELD_Method];
	[copyDic setObject:[NSNumber numberWithInt:HO_SERVICE_CAIYUN] forKey:kHO_FIELD_Service];
	[copyDic setObject:CaiyunBaseUrl forKey:kHO_FIELD_FullUrl];
	
	if(needCheckAccessToken)
	{
		NSString *caiYunAccessToken = [HOGlobalData sharedInstance].caiYunAccessToken;
		if(caiYunAccessToken == NULL)
			return;
		[copyDic setObject:[HOGlobalData sharedInstance].caiYunAccessToken forKey:kCY_FIELD_AccessToken];
	}
	
	[self sendRequestWithParams:copyDic
					withModules:nil];
	[copyDic release];
}

- (void)sendCaiyunRequestWithParamsNeedCheckToken:(NSDictionary *)dic
{
	[self sendCaiyunRequestWithParams:dic withNeedCheckAccessToken:YES];
}

- (void)requestCaiyunAccessToken
{
	[self sendCaiyunRequestWithParams:@{kHO_FIELD_Action:kCY_ACTION_GetAccessToken,
										kCY_FIELD_AppId:CaiyunAppId,
										kCY_FIELD_AppSecret:CaiyunAppSecret,
										kCY_FIELD_Flags:[NSNumber numberWithInt:0]} withNeedCheckAccessToken:NO];
}


- (void)LoginCaiyun
{
	
	//微度
	//	[self sendCaiyunRequestWithParamsNeedCheckToken:@{kHO_FIELD_Action:kCY_ACTION_Login,
	//kCY_FIELD_Token:@"eyJhcHBJZCI6NjAyNTQ0NjksIm9yZ0lkIjoxNDQ1NTIsInNjb3BlSWQiOjUyNTQ1LCJzaWduYXR1cmUiOiJkYzUxNjQ1MzAwMzQ0YWZhODE5MzU4NDMyNzE3NTdhZCIsInNpdGVJZCI6MSwidGltZXN0YW1wIjoxNTA5MDA2NTMzNDIxLCJ1aWQiOiIxMDEwMTAwMTE5MzQ2MTEyMCJ9"}];
	
	
	//彩云"
	[self sendCaiyunRequestWithParamsNeedCheckToken:@{kHO_FIELD_Action:kCY_ACTION_Login,
													  kCY_FIELD_Token:@"eyJhcHBJZCI6NjAyNTQ0NjksIm9yZ0lkIjo1NzE3MTIxMDMxLCJzY29wZUlkIjoxNjc2LCJzaWduYXR1cmUiOiIxN2I4MTUxM2ZjOTNmOTVhMTAyMTU5YmE5ZTViZTJkYiIsInNpdGVJZCI6MSwidGltZXN0YW1wIjoxNTEwNzk4MzQzMzc0LCJ1aWQiOiIxMDEwMTAwMTE5MzQ2MTEyMCJ9"}];
}

- (void)checkoutCaiYunAddressBook
{
//	return;
	/*
	 名称	类型	必须	默认值	说明
	 accessToken	string	是		接口访问凭据
	 orgSecret	string	是		企业密钥，通过免登接口获取
	 uid	string	否		调用接口的用户Id
	 name	string	否		调用接口的用户姓名
	 */
	if(isSupportCaiYun)
	{
		
		[self sendCaiyunRequestWithParamsNeedCheckToken:@{kHO_FIELD_Action:kCY_ACTION_ExportContact,
														  kCY_FIELD_OrgSecret:[HOGlobalData sharedInstance].caiYunUser.orgSecret,
														  kCY_FIELD_Uid:[HOGlobalData sharedInstance].caiYunUser.uid,
														  kCY_FIELD_Name:[HOGlobalData sharedInstance].caiYunUser.name}];
	}
}

- (void)requestDepartmentList:(long)departmentId
{
	[self sendCaiyunRequestWithParamsNeedCheckToken:@{kHO_FIELD_Action:kCY_ACTION_GetDepartmentList,
													  kCY_FIELD_OrgSecret:[HOGlobalData sharedInstance].caiYunUser.orgSecret,
													  kCY_FIELD_DeptId:[NSNumber numberWithLong:departmentId]}];
}
- (void)requestUserListFromDepartmentId:(long)departmentId
{
	[self sendCaiyunRequestWithParamsNeedCheckToken:@{kHO_FIELD_Action:kCY_ACTION_GetUserListAll,
													  kCY_FIELD_OrgSecret:[HOGlobalData sharedInstance].caiYunUser.orgSecret,
													  kCY_FIELD_DeptId:[NSNumber numberWithLong:departmentId]}];
}

- (void)exportSYFAB:(NSDictionary *)abDic
{
//	return;
	self.caiyunABDic = abDic;
	NSArray *deptList = [abDic objectForKey:kCY_FIELD_DeptId];
	
		NSMutableDictionary *allDeptDic = [[[NSMutableDictionary alloc] init] autorelease];
		for(int i = 0; i < [deptList count]; i ++)
		{
			NSDictionary *dic = [deptList objectAtIndex:i];
	
			NSString *departmentId = [dic objectForKey:@"deptId"];
			NSString *name = [dic objectForKey:@"name"];
			NSString *parentId = [dic objectForKey:@"parentId"];
//			NSLog(@"++++++ deptId:%@ name:%@ parentId:%@" , deptId, name, parentId);
			if([departmentId isEqualToString:@"1153905"])
			{
				NSLog(@"debug");
			}
			if(name == nil)
			{
				name = @"no dept name";
			}
			if(departmentId != nil)
			{
				[allDeptDic setObject:dic forKey:departmentId];
			}
		}
	NSMutableArray *wrapDeptArray = [[NSMutableArray alloc] init];
	for(int i = 0; i < [deptList count]; i ++)
	{
		NSDictionary *dic = [deptList objectAtIndex:i];
		
		NSString *departmentId = [dic objectForKey:@"deptId"];
		if([departmentId isEqualToString:@"1153980"])
		{
			NSLog(@"abc");
		}
//		NSString *name = [dic objectForKey:@"name"];
		NSString *parentId = [dic objectForKey:@"parentId"];
		NSDictionary *rootParentDic = [self getRootParentId:parentId inAllDeptDic:allDeptDic];
//		NSLog(@"+++++ start ------- + deptId:%@ name:%@ parentId:%@" , deptId, name, parentId);
		NSMutableDictionary *wrapDic = [NSMutableDictionary dictionaryWithDictionary:dic];
		NSString *companyId = @"00100";
		if(rootParentDic)
		{
//			NSString *parentId = [rootParentDic objectForKey:kCY_FIELD_Parentid];
			NSString *name = [rootParentDic objectForKey:kCY_FIELD_Name];
			NSRange range = [name rangeOfString:@"下沙"];
			
			if(range.length > 0)
			{
				NSLog(@"+++++ find 00101  1153941 ------- + parent departmentId:%@ parent name:%@ locaiton:%d" , parentId, name, range.location);

				companyId = @"00101";
			}
		}
//		NSLog(@"+++++ end ----- ");
		[wrapDic setObject:companyId forKey:@"companyId"];
		[wrapDeptArray addObject:wrapDic];
	}
	
	SBJson5Writer *jsonWriter = [[SBJson5Writer alloc] init];
	NSString *deptListStr = [jsonWriter stringWithObject:wrapDeptArray];
	[self sendRequestWithParams:@{
								  kHO_FIELD_Action:kHO_ACTION_UploadDept,
								  kHO_FIELD_Password:@"c2783a36c6e2a3ee102ee9b724de28b8",//[@"hzwd" stringFromMD5],
								  @"deptList":[HOUtils getValideString:deptListStr]}];
	[wrapDeptArray release];
}

- (NSDictionary *)getRootParentId:(NSString *)parentId inAllDeptDic:(NSDictionary *)allDeptDic
{
//	NSLog(@" -----------    ");
	if(!parentId)
	{
//		NSLog(@" ------parentId = nil-----    ");
		return nil;
	}
	
	if(!allDeptDic)
	{
//		NSLog(@" ------allDeptDic = nil-----    ");
		return nil;
	}
	
	NSDictionary *parentDic = [allDeptDic objectForKey:parentId];
	NSDictionary *rootParentDic = nil;
	if(!parentDic)
	{
		
//		NSLog(@" ------parentDic = nil-----    ");
		return nil;
	}
	
	while (parentId && [parentId intValue] > 0)
	{
//		NSLog(@"++++++ parentId:%@ " , parentId);
		rootParentDic = [allDeptDic objectForKey:parentId];
		if(rootParentDic == nil)
		{
//			NSLog(@"++++++ parentDic = nil in while");
			break;
		}
//		NSLog(@"++++++ parentDic:%@ " , parentDic);
		
		parentId = [rootParentDic objectForKey:kCY_FIELD_Parentid];
		NSString* name = [rootParentDic objectForKey:kCY_FIELD_Name];
//		NSLog(@"++++++ parentId:%@ parentName:%@" , parentId, name);
	}
	return rootParentDic;
}

- (void)uploadUserList
{
	NSArray *deptList = [self.caiyunABDic objectForKey:kCY_FIELD_DeptList];
	SBJson5Writer *jsonWriter = [[SBJson5Writer alloc] init];
	//	NSString *deptListStr = [jsonWriter stringWithObject:deptList];
	
	
	NSArray *userList = [self.caiyunABDic objectForKey:kCY_FIELD_UserList];
	NSString *orgId = [self.caiyunABDic objectForKey:kCY_FIELD_OrgId];
	NSMutableArray *editUserList = [[NSMutableArray alloc] init];
	
	NSMutableDictionary *allDeptDic = [[[NSMutableDictionary alloc] init] autorelease];
	for(int i = 0; i < [deptList count]; i ++)
	{
		NSDictionary *dic = [deptList objectAtIndex:i];
		
		NSString *departmentId = [dic objectForKey:@"deptId"];
		NSString *name = [dic objectForKey:@"name"];
		NSLog(@"++++++ departmentId:%@ name:%@" , departmentId, name);
		if([departmentId isEqualToString:@"1153905"])
		{
			NSLog(@"debug");
		}
		if(name == nil)
		{
			name = @"no dept name";
		}
		if(departmentId != nil)
		{
			[allDeptDic setObject:name forKey:departmentId];
		}
		
	}
	
	NSLog(@"1951056:%@", [allDeptDic objectForKey:@"1951056"] );
	int times = 0;
	for(int i = 0; i < [userList count]; i ++)
	{
		NSDictionary *dic = [userList objectAtIndex:i];
		NSString *mobile = [dic objectForKey:@"mobile"];
		NSString *name = [dic objectForKey:@"name"];
		NSString *departmentId = [dic objectForKey:@"deptId"];
		NSString *virtualCellPhone = [dic objectForKey:@"virtualCellPhone"];
		if(mobile == nil || [mobile isEqualToString:@""])
		{
			NSLog(@"++++++ name:%@" , name);
			times ++;
			if(departmentId != nil)
			{
				NSString *deptName = [ allDeptDic objectForKey:departmentId];
				NSLog(@"deptName:%@", deptName);
			}
			NSLog(@"info:%@", dic);
			mobile = virtualCellPhone;
		}
		if(mobile && [mobile length] > 0)
		{
			NSMutableDictionary *editDic = [NSMutableDictionary dictionaryWithDictionary:dic];
			[editDic setObject:mobile forKey:@"mobile"];
			[editUserList addObject:editDic];
		}
		
	}
	NSString *userListStr = [jsonWriter stringWithObject:editUserList];
	
	
	
	UIDevice *device = [UIDevice currentDevice];
	NSString *deviceID = [device uniqueDeviceIdentifier] == nil ? @"" : [device uniqueDeviceIdentifier];
	
	[self sendRequestWithParams:@{
								  kHO_FIELD_Action:kHO_ACTION_RegisterUser,
								  kCY_FIELD_OrgId:[HOUtils getValideString:orgId],
								  kCY_FIELD_UserList:[HOUtils getValideString:userListStr],
								  kHO_FIELD_Password:@"c2783a36c6e2a3ee102ee9b724de28b8",//[@"hzwd" stringFromMD5],
								  kHO_FIELD_CompanyID:@"10010",
								  kHO_FIELD_DeviceId:[HOUtils getValideString:deviceID],
								  kHO_FIELD_OSType:@"1",
								  kHO_FIELD_PhoneType:[NSNumber numberWithInt:1],
								  kHO_FIELD_OSVersion:[device systemVersion],
								  kHO_FIELD_RegistrationID:[[HOJPushHandler sharedInstance] getRegistertationID],}];
	
	[jsonWriter release];
}

- (void)didReceiveResponse:(HOBaseResponseEntity *)response
{
	[super didReceiveResponse:response];
	if([response isRequestDone])
	{
		[[self getDataModule] didReceiveResponse:response];
		[self handleResponseLogic:response];
		if([response.action isEqualToString:kHO_ACTION_UploadDept])
		{
			[self uploadUserList];
		}
	}
}
@end
